import { initializeApp } from "firebase/app";
import { getAnalytics, setUserId, logEvent } from "firebase/analytics";
import * as MITO from "@zhj1214/qdjk-web";
import { EActionType, Severity } from "@zhj1214/qdjk-types";
import { useUserStore } from "~~/store/modules/user";

export const useInitFirebase = () => {
  try {
    if (process.server) return null;

    const firebaseConfig = {
      apiKey: "AIzaSyBCbltwinDcwdz_9FA2tSr7rViBwTioGKQ",
      authDomain: "btcdanan.firebaseapp.com",
      databaseURL: "https://btcdanan.firebaseio.com",
      projectId: "btcdanan",
      storageBucket: "btcdanan.appspot.com",
      messagingSenderId: "803913689494",
      appId: "1:803913689494:web:964738ab19efc96aa655b7",
      measurementId: "G-BGTVFX7FPQ",
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
    const userStore = useUserStore();

    return {
      logEvent: (eventName: string, params?: any) => {
        try {
          logEvent(analytics, eventName, params);
          // 在谷歌埋点的同时增加自己的埋点事件 const { userId = '', eventKey = 'BDC', level = Severity.Info, params = {} } = data.param
          MITO.track(EActionType.EVENT, {
            userId: userStore.$state.sid,
            eventKey: eventName,
            level: Severity.Info,
            params,
          });
        } catch (error) {
          console.log(error);
        }
      },
      setUserId: (userId: string) => {
        try {
          setUserId(analytics, userId);
        } catch (error) {
          console.log(error);
        }
      },
    };
  } catch (error) {
    console.log(error);
  }

  return null;
};
